package chapter5.homework.oldSeries.Q2weekdayTranslate;

import java.io.*;
import java.net.Socket;
import java.util.HashMap;
import java.util.Scanner;

/**
 * @Project ：learn_java
 * @File ：Client.java
 * @IDE ：IntelliJ IDEA
 * @Author ：自由如风间
 * @Date ：2025/3/17 15:45
 * @Description ：For study.
 */

public class Client {
    public static void main(String[] args) throws IOException {
        String localhost = "127.0.0.1";
        int defaultPort = 10000;
        // 创建socket对象并连接服务端
        Socket socket = new Socket(localhost, defaultPort);

        // 构建IO
        InputStream is = socket.getInputStream();
        OutputStream os = socket.getOutputStream();

        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(os));
        // 向服务器端发送一条消息

        HashMap<Integer, String> mp = new HashMap<>() {{
            put(1,"星期一");
            put(2,"星期二");
            put(3,"星期三");
            put(4,"星期四");
            put(5,"星期五");
            put(6,"星期六");
            put(7,"星期日");
        }};

        Scanner scanner = new Scanner(System.in);

        String queryDay;

        while (true) {
            System.out.print("从1到7输入一个数字，表示你需要查询的星期：");
            try {
                String input = scanner.nextLine();
                int i = Integer.parseInt(input, 10);
                if (input.length() != 1 || (i > 7 || i < 1)) {
                    throw new IllegalArgumentException("输入的数字必须是 1 到 7 之间的一位数！");
                }
                // 这里可以添加处理有效输入的逻辑
                System.out.println("你查询的是：" + mp.get(i));
                queryDay = mp.get(i);
                break;
            } catch (NumberFormatException e) {
                System.out.println("请输入有效的数字！");
            } catch (IllegalArgumentException e) {
                System.out.println(e.getMessage());
            }
        }

        // 发送查询的中文
        // 因为server使用的是readLine，所有这里要做换行符处理，才能使服务器停止读取
        bw.write(queryDay + "\n");
        bw.flush();

        // 读取服务器返回的消息
        BufferedReader br = new BufferedReader(new InputStreamReader(is));
        String mess = br.readLine();
        System.out.println("服务器：" + mess);
    }
}
